<template>
  <div>
    <div :id="id" class="yl-group-group"></div>
  </div>
</template>

<script>
import AMap from 'AMap'
import { createRandomId } from '@/utils/index'
export default {
  name: 'YlGroup',
  data () {
    return {
      id: createRandomId(),
      map: '',
      lng: '',
      lat: ''
    }
  },
  mounted () {
    this.getLocation()
    this.initMap()
  },

  methods: {
    initMap () {
      this.map = new AMap.Map(this.id, {
        lang: 'zh_cn',
        zoom: 18,
        center: [104.07185, 30.65371],
        viewMode: '3D',
        resizeEnable: true
      })

      AMap.service(['AMap.ToolBar', 'AMap.Scale', 'AMap.Autocomplete'], () => {
        // 添加缩放条及移动盘
        this.map.addControl(new AMap.ToolBar())
        // 添加比例尺
        this.map.addControl(new AMap.Scale())

        const position = this.map.getCenter()

        // 创建可移动的MAP_MARKER标点
        this.marker = new AMap.Marker({
          position: position,
          offset: new AMap.Pixel(-15, -10),
          draggable: false,
          cursor: true,
          raiseOnDrag: false,
          zIndex: 101
        })

        this.marker.setMap(this.map)
        this.map.setCenter(position)
      })
    },

    // 通过ip获取当前经纬度
    getLocation () {
      AMap.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true
        })

        geolocation.getCurrentPosition()
        AMap.event.addListener(geolocation, 'complete', onComplete)

        function onComplete (data) {
          this.lng = data.position.lng
          this.lat = data.position.lat
          console.log(this.lng, this.lat)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .yl-group-group {
    width: 75em;
    height: 40em;
  }
</style>
